import Vue from 'vue'
import store from './store'
import App from './App'

import {
	myRequest
} from '@/common/api.js'


// 头部
import Header from '@/components/header/header.vue';
Vue.component('Header', Header);

//表单验证
import bjxForm from '@/components/bjx-form/bjx-form.vue';
import bjxFormItem from '@/components/bjx-form/bjx-form-item.vue'
Vue.component('bjxForm', bjxForm);
Vue.component('bjxFormItem', bjxFormItem);

import UniNavBar from '@/components/uni-nav-bar'
Vue.component('UniNavBar', UniNavBar);

import uView from '@/uni_modules/uview-ui'
Vue.use(uView)

/**
 *  因工具函数属于公司资产, 所以直接在Vue实例挂载几个常用的函数
 *  所有测试用数据均存放于根目录json.js
 *  
 *  css部分使用了App.vue下的全局样式和iconfont图标，有需要图标库的可以留言。
 *  示例使用了uni.scss下的变量, 除变量外已尽量移除特有语法,可直接替换为其他预处理器使用
 */

const Rad = (d) => {
	return d * Math.PI / 180.0;
}

const getMapDistance = (lat1, lng1, lat2, lng2) => {
	var radLat1 = Rad(lat1);
	var radLat2 = Rad(lat2);
	var a = radLat1 - radLat2;
	var b = Rad(lng1) - Rad(lng2);
	var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) +
		Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));
	s = s * 6378.137; // EARTH_RADIUS;
	s = Math.round(s * 10000) / 10000; //输出为公里
	s = s.toFixed(2);
	return s;
}

const msg = (title, icon = 'none', duration = 1500, mask = false) => {
	//统一提示方便全局修改
	if (Boolean(title) === false) {
		return;
	}
	uni.showToast({
		title,
		duration,
		mask,
		icon
	});
}



/** 删除对象空属性
 * @method deleteObjNull
 * @param {Object} obj 要处理的对象
 */
const deleteObjNull = (obj) => {
	for (let key in obj) {
		if (obj[key] === '' || obj[key] === undefined || obj[key] === null || obj[key] == '-' || obj[key] ==
			'NaN') {
			delete obj[key];
		}
	}
}

/** 判断用户是否登录
 * @method isLogin
 * @param {Boolean} forcedLogin 是否需要强制登录,默认为false
 * @param {Boolean} relaunch 是否关闭所有页面，再打开新页面,默认为false
 */
const isLogin = () => {
	if (store.state.hasLogin === false) {
		msg('尚未登录，请先登录！');
		setTimeout(() => {
			uni.reLaunch({
				url: '/pages/login/login'
			})
		}, 600)

		return false;
	}
	return true;
}

// 复制和重置state,用于退出时重置vuex值
const copyResetState = (type) => {
	if (type) {
		// 退出时重置
		store.commit('resetState', JSON.parse(Vue.prototype.stateStr));
	} else {
		// main.js中初始化复制
		Vue.prototype.stateStr = JSON.stringify(store.state);
	}
}

// 退出登录
const userLoginOut = () => {
	copyResetState(true); //重置vuex
	store.commit('setUserInfo', {});
	uni.removeStorage({
		key: 'userInfo'
	})
	uni.navigateTo({
		url: '/pages/index'
	})
}

/** 获取验证码
 * @method getVerificationCode
 * @param {String} username 手机号，用于验证号码是否合规
 * @param {String} codeUrl 请求的接口地址
 * @param {Object} obj 请求发送的数据
 */
const getVerificationCode = (username, codeUrl, obj, countFn) => {
	//定义表单规则
	const rule = [{
		name: "username",
		checkType: "phoneno",
		checkRule: "11",
		errorMsg: "请输入正确的手机号码"
	}, ];
	let checkRes = graceChecker.check({
		'username': username
	}, rule); //验证手机号

	if (checkRes) {
		store.state.securityTimeDec = true;
		// 发送请求获取验证码
		uniRequest(codeUrl, obj, res => {
			if (countFn) {
				countFn();
			} else {
				countDown();
			}
		})
	} else {
		uni.showToast({
			title: graceChecker.error,
			icon: "none"
		});
	}
}

// 验证码倒计时
const countDown = () => {
	store.state.securityTime = 89;
	let invalId = setInterval(() => {
		//发送验证码倒计时
		store.state.securityTime--;
		if (store.state.securityTime == 0 || !store.state.securityTimeDec) {
			clearInterval(invalId);
			store.state.securityTime = 90;
		}
	}, 1000);
}


/* 格式化时间
 * @method fmtDate
 * @param {String} str 时间戳字符串
 * @param {String} d 日期格式，默认为时间格式,1年月日,2月日时分,3年月1号
 * @return {String} 返回格式化之后的日期
 */
const fmtDate = (str, d) => {
	let dt = str ? new Date(str) : new Date();
	let year = dt.getFullYear();
	let month = fixed2(dt.getMonth() + 1);
	let date = fixed2(dt.getDate());
	let hours = fixed2(dt.getHours());
	let minutes = fixed2(dt.getMinutes());
	let secounds = fixed2(dt.getSeconds());
	let times = '';
	if (d == 1) {
		times = `${year}-${month}-${date}`;
	} else if (d == 2) {
		times = `${month}-${date} ${hours}:${minutes}`;
	} else if (d == 3) {
		times = `${year}-${month}-01`;
	} else {
		times = `${year}-${month}-${date} ${hours}:${minutes}:${secounds}`;
	}
	return times;
}

//停止当前页面下拉刷新
const stopPullRefresh = () => {
	setTimeout(() => {
		uni.stopPullDownRefresh();
	}, 800)
}

// 向上保留两位小数
const ceilFixed2 = (num) => {
	let ceilNum = Math.ceil(num * 100) / 100;
	return ceilNum.toFixed(2);
}


// 预览图片
const previewImg = (arr, current) => {
	uni.previewImage({
		urls: arr,
		current: current
	})
}


const json = type => {
	//模拟异步请求数据
	return new Promise(resolve => {
		setTimeout(() => {
			resolve(Json[type]);
		}, 500)
	})
}

const prePage = () => {
	let pages = getCurrentPages();
	let prePage = pages[pages.length - 2];
	// #ifdef H5
	return prePage;
	// #endif
	return prePage.$vm;
}


Vue.config.productionTip = false
Vue.prototype.$fire = new Vue();
Vue.prototype.$store = store;
Vue.prototype.$api = {
	msg,
	isLogin,
	stopPullRefresh,
	json,
	prePage,
	getMapDistance
};
Vue.prototype.$myRequest = myRequest;

const downLoadUrl = "https://liande.oss-cn-beijing.aliyuncs.com/download/%E5%BB%89%E5%BE%B7%E5%8A%B3%E5%8A%A1.apk";
Vue.prototype.$downLoadUrl = downLoadUrl;

const downLoadIosUrl = "https://www.pgyer.com/LDLW";
Vue.prototype.$downLoadIosUrl = downLoadIosUrl;

const totalList = 113;
Vue.prototype.$totalList = totalList;

// #ifdef H5
import wechat from '@/common/wechat.js'
if (wechat.isWechat()) {
	Vue.prototype.$wechat = wechat;
}


//mian.js 加入这两句
const jweixin = require('jweixin-module')
Vue.prototype.$wx = jweixin
// #endif

App.mpType = 'app'

const app = new Vue({
	...App
})

//http拦截器，此为需要加入的内容，如果不是写在common目录，请自行修改引入路径
// import httpInterceptor from '@/common/http.interceptor.js'
// // 这里需要写在最后，是为了等Vue创建对象完成，引入"app"对象(也即页面的"this"实例)
// Vue.use(httpInterceptor, app)

// // http接口API集中管理引入部分
// import httpApi from '@/common/http.api.js'
// Vue.use(httpApi, app)

app.$mount()
